/**
 * 
 */
package component.jfileexplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import javax.swing.tree.TreeNode;

public class FileNode implements TreeNode {

	/**
	 * 
	 */
	private final JFileExplorer jFileExplorer;
	FileNode parent;
	File file;
	List<File> child;
	
	public FileNode(JFileExplorer jFileExplorer, FileNode parent, File file) {
		this.jFileExplorer = jFileExplorer;
		this.parent = parent;
		this.file = file;
		updateChildren();
	}
	
	private void updateChildren()
	{
		child = new ArrayList<File>();
		if (file.isDirectory()) {
			File[] list = file.listFiles(this.jFileExplorer.filter);
			if (list == null) return;
			for (File f : list) child.add(f);
			Collections.sort(child);
		}
	}
	
	@Override
	public String toString() {
		return file.getName();
	}
	
	@Override
	public Enumeration children() {
		return new Vector<File>(child).elements();
	}

	@Override
	public boolean getAllowsChildren() {
		return file.isDirectory();
	}

	@Override
	public TreeNode getChildAt(int childIndex) {
		return new FileNode(this.jFileExplorer, this, child.get(childIndex));
	}

	@Override
	public int getChildCount() {
		return child.size();
	}

	@Override
	public int getIndex(TreeNode node) {
		if (node instanceof FileNode) {
			FileNode fn = (FileNode) node;
			return child.indexOf(fn.file);
		} 
		return -1;
	}

	@Override
	public TreeNode getParent() {
		return parent;
	}

	@Override
	public boolean isLeaf() {
		return !file.isDirectory();
	}

	public File getFile() {
		return file;
	}
	
}